package com.voicechat.firstmet.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.IMessageActivity;
import com.voicechat.firstmet.activity.PersonalHomepageActivity;
import com.voicechat.firstmet.activity.PostDetailsActivity;
import com.voicechat.firstmet.activity.SearchActivity;
import com.voicechat.firstmet.activity.SendPostActivity;
import com.voicechat.firstmet.activity.SystemNotificationActivity;
import com.voicechat.firstmet.adapter.CommunityAdapter;
import com.voicechat.firstmet.base.BaseFragment;
import com.voicechat.firstmet.bean.CommBean;
import com.voicechat.firstmet.bean.CoummunityNotice;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PostBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.imcontrol.BroadcastManager;
import com.voicechat.firstmet.imcontrol.MediaUtil;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.CommunityService;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.AnimationUtils;
import com.voicechat.firstmet.utils.ConstantSet;
import com.voicechat.firstmet.utils.FileUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.ThreadManager;
import com.voicechat.firstmet.utils.Utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 社区
 * Created by Administrator on 2018/8/28.
 */
public class CommunityFragment extends BaseFragment  {
    @BindView(R.id.image_search)
    ImageView imageSearch;
    @BindView(R.id.image_im_list)
    ImageView imageImList;
    @BindView(R.id.recycler_list)
    RecyclerView recyclerList;
    @BindView(R.id.floatin_button)
    ImageView floatinButton;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.image_read)
    ImageView imageRead;
    private String TAG = "CommunityFragment";
    //热门信息数据list
    private ArrayList<CommBean.MapBean> commBeans = new ArrayList<>();
    private ArrayList<CoummunityNotice.PageBean.ListBean> coummunityNotices = new ArrayList<>();
    private ArrayList<PostBean.PageBean.ListBean> postLists = new ArrayList<>();
    private CommunityAdapter communityAdapter;
    private boolean visible = true;//是否可见，判断是否显示发送帖子按钮
    private int page;//页数，用于初见广场分页加载
    private String token;
    private String deviceInfo;
    Runnable runnable;
    private String userId;
    public static MySelfInfoBean.ObjectBean mySeleInfo;

    @Override
    protected int loadLayout() {
        return R.layout.fragment_communite;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this, view);
        initView();
        //请求数据
        httpNotice();
        communityPostList();
        httpHotInfo();
        //获取系统消息未读
        httpMsgSystem();
    }
    //获取系统消息未读
    private void httpMsgSystem() {
        MeInfoService.systemMessage(mySeleInfo.getId(), token, deviceInfo, "","1").subscribe(coummunityNotice -> {
            // Log.i(TAG, "setHttpData: ----"+coummunityNotice.getPage().getList().size());
            if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                Log.i(TAG, "setHttpData: ---getCount---"+coummunityNotice.getPage().getCount());
                setMsgUnread(coummunityNotice.getPage().getCount() == 0?true:false);
            } else if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(coummunityNotice.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "setHttpData: ----" + throwable.toString());
            toast_MakeText(getResources().getString(R.string.net_error));
        });
    }

    @Override
    public void onResume() {
        //获取系统消息未读
        httpMsgSystem();
        super.onResume();
    }

    /**
     * @return
     * @method
     * @description 布局数据实例化
     * @date: 2018/10/12 18:09
     * @author: ljp
     */
    private void initView() {
        BroadcastManager.getInstance(context).addAction("msg", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int result = intent.getIntExtra("rresult", 0);
                Log.i(TAG, "onReceive: -------result-----"+result);
                setMsgUnread(result == 0);
            }
        });
        page = 1;
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        userId = mySeleInfo.getId();
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                httpNotice();
                communityPostList();
                httpHotInfo();
                httpMsgSystem();
                smartRefresh.finishRefresh(10000);
            }
        });
        //上拉加载更多
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                communityPostList();
                smartRefresh.finishLoadMore(10000);
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        AnimationUtils.showFABAnimation(floatinButton);
        communityAdapter = new CommunityAdapter(context, postLists, R.layout.item1_community, "");
      //  communityAdapter.addHeaderView(R.layout.fragment_list_head);
        recyclerList.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
       // recyclerList.setAdapter(communityAdapter);
        // 第一种，直接取消动画
        RecyclerView.ItemAnimator animator = recyclerList.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        recyclerList.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //获取当前recyclerView的布局管理器
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();//获取当前可见的最后一个posttion
                if (dy > 0 && !visible) {//下滑
                    //显示
                    AnimationUtils.showFABAnimation(floatinButton);
                    visible = true;
                } else if (dy <= 0 && visible && lastVisibleItemPosition == 1) {//上滑且当当前可见的最后一个position为1时隐藏
                    //隐藏
                    AnimationUtils.hideFABAnimation(floatinButton);
                    visible = false;
                }
            }
        });
        communityAdapter.setItemSetClick(new CommunityAdapter.ItemSetClick() {
            //个人主页
            @Override
            public void setIconClick(View view, PostBean.PageBean.ListBean listBean) {
                Intent intent = new Intent(context, PersonalHomepageActivity.class);
                intent.putExtra("anchorId", listBean.getUserId());
                context.startActivity(intent);
            }

            @Override
            public void setIconClick(View view, CommBean.MapBean.DynamicBean dynamic) {
                Intent intent = new Intent(context, PersonalHomepageActivity.class);
                intent.putExtra("anchorId", dynamic.getUserId());
                context.startActivity(intent);
            }

            //帖子详情
            @Override
            public void setItemClick(View view, PostBean.PageBean.ListBean listBean) {
                //Log.i(TAG, "setItemClick: ----------"+listBean.toString());
                Intent intent = new Intent(context, PostDetailsActivity.class);
                intent.putExtra("listBean", listBean);
                startActivity(intent);
            }

            //热门帖子点赞
            @Override
            public void setLikeClick(View view, CommBean.MapBean.DynamicBean dynamic) {
                CommunityService.postLikeAndUnLike(token, deviceInfo, dynamic.getHotId(),
                        CommunityService.LIKE_TYPE.LIKE_POST_TYPE, userId).subscribe(result -> {
                    if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                        if (!TextUtils.isEmpty(dynamic.getIsFabulous()) && dynamic.getIsFabulous().equals("0")) {// 1 已经点赞   0 未点赞
                            dynamic.setIsFabulous("1");
                            dynamic.setFabulousCount(dynamic.getFabulousCount() + 1);
                        } else if (!TextUtils.isEmpty(dynamic.getIsFabulous()) && dynamic.getIsFabulous().equals("1")) {
                            dynamic.setIsFabulous("0");
                            dynamic.setFabulousCount(dynamic.getFabulousCount() - 1);
                        }
                        communityAdapter.notifyDataSetChanged();
                    } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                        Utils.setToken(context);
                    } else {
                        toast_MakeText(result.getMsg());
                    }
                }, throwable -> {
                    Log.i(TAG, "setLikeClick: -------" + throwable.toString());
                });
            }

            //帖子点赞
            @Override
            public void setLikeClick(View view, PostBean.PageBean.ListBean listBean) {
                CommunityService.postLikeAndUnLike(token, deviceInfo, listBean.getId(),
                        CommunityService.LIKE_TYPE.LIKE_POST_TYPE, userId).subscribe(result -> {
                    if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                        if (listBean.getIsFabulous().equals("0")) {//0未点赞 1 点赞
                            listBean.setIsFabulous("1");
                            listBean.setFabulousCount(listBean.getFabulousCount() + 1);
                        } else if (listBean.getIsFabulous().equals("1")) {
                            listBean.setIsFabulous("0");
                            listBean.setFabulousCount(listBean.getFabulousCount() - 1);
                        }
                        communityAdapter.notifyDataSetChanged();
                    } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                        Utils.setToken(context);
                    } else {
                        toast_MakeText(result.getMsg());
                    }
                    // Log.i(TAG, "setLikeClick: -------"+result.toString());
                }, throwable -> {
                    // Log.i(TAG, "setLikeClick: -------"+throwable.toString());
                });
            }
            //热门帖子
            @Override
            public void setItemClick(View view, CommBean.MapBean.DynamicBean dynamic) {
                PostBean.PageBean.ListBean listBean = new PostBean.PageBean.ListBean(dynamic.getHotId(), dynamic.isNewRecord(),
                        dynamic.getMdTitle(), dynamic.getContent(), dynamic.getMdUpdateDate(), dynamic.getUserId(),
                        dynamic.getAvatarUrl(), dynamic.getNickName(), dynamic.getGender(), dynamic.getBirthday(),
                        dynamic.getFabulousCount(), dynamic.getDiscussCount(), dynamic.getIsFabulous(), dynamic.getvType(),
                        dynamic.getuType(), dynamic.getUrl(), dynamic.getWarrant(), dynamic.getIsFollow(), dynamic.getVoiceUrl(), dynamic.getDuration());
                Intent intent = new Intent(context, PostDetailsActivity.class);
                intent.putExtra("listBean", listBean);
                startActivity(intent);
            }

            @Override
            public void setNoticeClick(View view, List<CoummunityNotice.PageBean.ListBean> notices) {
                Intent intent = new Intent(activity, SystemNotificationActivity.class);
                intent.putParcelableArrayListExtra("notice", (ArrayList<? extends Parcelable>) notices);
                startActivity(intent);
            }

            //播放语音
            @Override
            public void setPlayVoiceClick(PostBean.PageBean.ListBean listBean, View view, int position,View imagePlay) {
                String path = ConstantSet.VOICEINTR + ConstantSet.VOICE_POST + Utils.getVoiceName(listBean.getVoiceUrl());
                Log.i(TAG, "onBindViewHolder: -----" + path);
                if (FileUtils.isExists(path)) {
                    try {
                        player(path, (ImageView) view, position);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void setPlayVoiceClick(CommBean.MapBean.DynamicBean dynamic, View view, int position) {
                String path = ConstantSet.VOICEINTR + ConstantSet.VOICE_POST + Utils.getVoiceName(dynamic.getVoiceUrl());
                Log.i(TAG, "onBindViewHolder: -----" + path);
                if (FileUtils.isExists(path)) {
                    try {
                        player(path, (ImageView) view, position);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void setItemClickShare(View view, PostBean.PageBean.ListBean listBean) {

            }
        });
        floatinButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, SendPostActivity.class));
            }
        });
    }

    int mFirstVoicePlayItem;//第一级列表的喇叭动画初始位置
    int mSecondVoicePlayItem;//第二级列表的喇叭动画初始位置
    //int position;//当前列表的位置
    AnimationDrawable animationDrawable;
    ImageView imageViewIconVoice;

    /**
     * @return
     * @method
     * @description 播放语音
     * @date: 2018/9/28 18:57
     * @author: ljp
     */
    private void player(String path, ImageView imageView, int position) throws FileNotFoundException {
        imageViewIconVoice = imageView;
        if (TextUtils.isEmpty(path)) {
            return;
        }
        mSecondVoicePlayItem = -1;
        if (animationDrawable != null) {
            MediaUtil.getInstance().stop();
            animationDrawable.stop();
            animationDrawable.selectDrawable(2);
            animationDrawable = null;
            if (mFirstVoicePlayItem != position) {
                mFirstVoicePlayItem = position;
                imageView.setImageResource(R.drawable.post_voice);
                animationDrawable = (AnimationDrawable) imageView.getDrawable();
                animationDrawable.start();
                MediaUtil.getInstance().play(new FileInputStream(path));
            }
        } else {
            mFirstVoicePlayItem = position;
            imageView.setImageResource(R.drawable.post_voice);
            animationDrawable = (AnimationDrawable) imageView.getDrawable();
            animationDrawable.start();
            MediaUtil.getInstance().play(new FileInputStream(path));
        }
        MediaUtil.getInstance().getPlayer().setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.stop();
                if (animationDrawable != null) {
                    animationDrawable.stop();
                    animationDrawable.selectDrawable(2);
                    animationDrawable = null;
                }

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    /**
     * @return
     * @method
     * @description 启动线程池下载语音信息
     * @date: 2018/10/16 14:30
     * @author: ljp
     */
    private void setThreadPost(List<PostBean.PageBean.ListBean> postBeans) {
        ThreadManager.getThreadPool().execute(runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < postBeans.size(); i++) {
                    if (!TextUtils.isEmpty(postBeans.get(i).getVoiceUrl())) {
                        String voiceInfo = postBeans.get(i).getVoiceUrl();
                        int finalI = i;
                        OssClient.getInstance().init(context).fileDownload(voiceInfo, new OssClient.OnDownloadFile() {
                            @Override
                            public void onDownFileSuccess(InputStream inputStream) {
                                String voiceName = Utils.getVoiceName(postBeans.get(finalI).getVoiceUrl());
                                //Log.i(TAG, "onDownFileSuccess: ---------"+voiceName);
                                String path = ConstantSet.VOICEINTR;
                                try {
                                    OssConfig.writeToLocalPost(path, inputStream, voiceName);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onDownFileProgress(String progress) {
                                //Log.i(TAG, "onDownFileProgress: ----------"+progress);
                            }
                        });
                    }
                }
            }
        });
    }

    /**
     * @return
     * @method
     * @description 请求公告信息
     * @date: 2018/10/9 13:52
     * @author: ljp
     */
    private void httpNotice() {
        CommunityService.communityNotice(token, deviceInfo).subscribe(coummunityNotice -> {
            Log.i(TAG, "httpNotice: -----------" + coummunityNotice);
            if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                coummunityNotices.clear();
                coummunityNotices.addAll(coummunityNotice.getPage().getList());
              //  communityAdapter.setNoticeList(coummunityNotices);
                communityAdapter.notifyDataSetChanged();
                smartRefresh.finishRefresh();
            } else if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(coummunityNotice.getMsg());
            }
        }, throwable -> {

        });
    }

    /**
     * @return
     * @method
     * @description 请求热门信息（banner、实时推荐、广告位、热门帖子）
     * @date: 2018/10/9 13:52
     * @author: ljp
     */
    private void httpHotInfo() {
        CommunityService.communityHotInfo(token, deviceInfo, userId).subscribe(coummunityNotice -> {
            Log.i(TAG, "httpHotInfo: -----------" + coummunityNotice.getCode());
            if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                commBeans.clear();
                commBeans.add(coummunityNotice.getMap());
                //Log.i(TAG, "httpNotice: ---------" + commBeans.get(0).getDynamic().toString());
                communityAdapter.notifyDataSetChanged();
                smartRefresh.finishRefresh();
                //setThread();//启动线程池下载主播头像
            } else if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(coummunityNotice.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "httpHotInfo: -------" + throwable.toString());
        });
    }

    /**
     * @return
     * @method
     * @description 请求帖子信息
     * @date: 2018/10/9 13:52
     * @author: ljp
     */
    private void communityPostList() {
        CommunityService.communityPostList(token, deviceInfo, page + "", userId).subscribe(postBean -> {
            Log.i(TAG, "communityPostList: ----------" + postBean.getCode());
            if (postBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                int i = postBean.getPage().getCount() / postBean.getPage().getPageSize() +
                        (postBean.getPage().getCount() % postBean.getPage().getPageSize() == 0 ? 0 : 1);
                if (page > i) {//判断是否是最后一页{//判断是否是最后一页
                    smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                    Log.i(TAG, "communityPostList: -------------postLists.size();--------" + postLists.size());
                } else {
                    if (page == 1) {
                        postLists.clear();
                        smartRefresh.finishRefresh();
                    }
                    postLists.addAll(postBean.getPage().getList());
                    communityAdapter.notifyDataSetChanged();
                    smartRefresh.finishLoadMore();
                    setThreadPost(postBean.getPage().getList());
                }
            } else if (postBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(postBean.getMsg());
            }
        }, throwable -> {

        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        ThreadManager.getThreadPool().cancel(runnable);
    }


    @OnClick({R.id.image_search, R.id.image_im_list})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_search:
                startActivity(new Intent(activity, SearchActivity.class));
                break;
            case R.id.image_im_list:
                startActivity(new Intent(activity, IMessageActivity.class));
                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            setOriginalImage();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        setOriginalImage();
    }

    //设置默认背景图片
    private void setOriginalImage() {
        if (animationDrawable != null) {
            MediaUtil.getInstance().getPlayer().stop();
            animationDrawable.stop();
            animationDrawable.selectDrawable(2);
            animationDrawable = null;
            imageViewIconVoice.setImageResource(R.mipmap.send_post_voice_icon3);
        }
    }
    /**
     * 设置未读tab显示
     */
    public void setMsgUnread(boolean noUnread){
        imageRead.setVisibility(noUnread?View.GONE:View.VISIBLE);
    }
}
